package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.StudentClassTeacherDTO;
import com.zhentao.pojo.TcClass;
import com.zhentao.service.TcClassService;
import com.zhentao.config.Result;
import com.zhentao.config.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("tea/class")
public class ClassController {

    @Autowired
    TcClassService classService;

    /**
     * 获取全部班级
     */
    @GetMapping("list")
    public List<TcClass> list(){
        return classService.list();
    }

    /**
     * 根据ID获取班级详情
     */
    @GetMapping("get/{id}")
    public TcClass getById(@PathVariable Integer id){
        return classService.getById(id);
    }

    /**
     * 添加班级
     */
    @PostMapping("add")
    public Map<String, Object> add(@RequestBody TcClass tcClass){
        Map<String, Object> result = new HashMap<>();
        try {
            tcClass.setCreateTime(new Date());
            boolean success = classService.save(tcClass);
            result.put("success", success);
            result.put("message", success ? "添加成功" : "添加失败");
            if (success) {
                result.put("data", tcClass);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 更新班级
     */
    @PutMapping("update")
    public Map<String, Object> update(@RequestBody TcClass tcClass){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = classService.updateById(tcClass);
            result.put("success", success);
            result.put("message", success ? "更新成功" : "更新失败");
            if (success) {
                result.put("data", tcClass);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除班级
     */
    @DeleteMapping("delete/{id}")
    public Map<String, Object> delete(@PathVariable Integer id){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = classService.removeById(id);
            result.put("success", success);
            result.put("message", success ? "删除成功" : "删除失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据创建者ID获取班级
     */
    @GetMapping("myClasses/{creatorUserId}")
    public List<TcClass> getMyClasses(@PathVariable Integer creatorUserId){
        QueryWrapper<TcClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("creator_user_id", creatorUserId);
        queryWrapper.orderByDesc("create_time");
        return classService.list(queryWrapper);
    }

    /**
     * 根据年级获取班级
     */
    @GetMapping("byGrade/{grade}")
    public List<TcClass> getByGrade(@PathVariable String grade){
        QueryWrapper<TcClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("grade", grade);
        queryWrapper.orderByDesc("create_time");
        return classService.list(queryWrapper);
    }

    /**
     * 根据科目获取班级
     */
    @GetMapping("bySubject/{subject}")
    public List<TcClass> getBySubject(@PathVariable String subject){
        QueryWrapper<TcClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("subject", subject);
        queryWrapper.orderByDesc("create_time");
        return classService.list(queryWrapper);
    }

    /**
     * 搜索班级
     */
    @GetMapping("search")
    public List<TcClass> searchClasses(@RequestParam String keyword){
        QueryWrapper<TcClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("class_name", keyword).or().like("grade", keyword).or().like("subject", keyword);
        queryWrapper.orderByDesc("create_time");
        return classService.list(queryWrapper);
    }

    /**
     * 获取班主任班级
     */
    @GetMapping("headteacherClasses")
    public List<TcClass> getHeadteacherClasses(){
        QueryWrapper<TcClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_headteacher", 1);
        queryWrapper.orderByDesc("create_time");
        return classService.list(queryWrapper);
    }

    /**
     * 根据班级邀请码获取班级
     */
    @GetMapping("byCode/{classCode}")
    public TcClass getByClassCode(@PathVariable String classCode){
        QueryWrapper<TcClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_code", classCode);
        return classService.getOne(queryWrapper);

    }

    /**
     * 批量删除班级
     */
    @DeleteMapping("batchDelete")
    public Map<String, Object> batchDelete(@RequestBody List<Integer> ids){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = classService.removeByIds(ids);
            result.put("success", success);
            result.put("message", success ? "批量删除成功" : "批量删除失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 分页查询班级
     */
    @GetMapping("page")
    public Result<PageResult<TcClass>> getClassPage(@RequestParam(defaultValue = "1") Integer current,
                                                    @RequestParam(defaultValue = "10") Integer size,
                                                    @RequestParam(required = false) String keyword,
                                                    @RequestParam(required = false) String grade,
                                                    @RequestParam(required = false) String subject) {
        try {
            Page<TcClass> page = new Page<>(current, size);
            QueryWrapper<TcClass> queryWrapper = new QueryWrapper<>();
            
            // 关键词搜索
            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.like("class_name", keyword).or().like("class_code", keyword);
            }
            
            // 年级筛选
            if (grade != null && !grade.trim().isEmpty()) {
                queryWrapper.eq("grade", grade);
            }
            
            // 科目筛选
            if (subject != null && !subject.trim().isEmpty()) {
                queryWrapper.eq("subject", subject);
            }
            
            queryWrapper.orderByDesc("create_time");
            
            Page<TcClass> result = classService.page(page, queryWrapper);
            
            PageResult<TcClass> pageResult = PageResult.of(
                (int) result.getCurrent(),
                (int) result.getSize(),
                result.getTotal(),
                result.getRecords()
            );
            
            return Result.success("分页查询班级成功", pageResult);
        } catch (Exception e) {
            return Result.error("分页查询班级失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询我的班级
     */
    @GetMapping("myClasses/page")
    public Result<PageResult<TcClass>> getMyClassesPage(@RequestParam Integer creatorUserId,
                                                        @RequestParam(defaultValue = "1") Integer current,
                                                        @RequestParam(defaultValue = "10") Integer size,
                                                        @RequestParam(required = false) String keyword) {
        try {
            Page<TcClass> page = new Page<>(current, size);
            QueryWrapper<TcClass> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("creator_user_id", creatorUserId);
            
            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.like("class_name", keyword).or().like("grade", keyword).or().like("subject", keyword);
            }
            
            queryWrapper.orderByDesc("create_time");
            
            Page<TcClass> result = classService.page(page, queryWrapper);
            
            PageResult<TcClass> pageResult = PageResult.of(
                (int) result.getCurrent(),
                (int) result.getSize(),
                result.getTotal(),
                result.getRecords()
            );
            
            return Result.success("分页查询我的班级成功", pageResult);
        } catch (Exception e) {
            return Result.error("分页查询我的班级失败：" + e.getMessage());
        }
    }

    /**
     * 获取班级统计信息
     */
    @GetMapping("statistics")
    public Result<Map<String, Object>> getClassStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 总班级数
            long totalClasses = classService.count();
            statistics.put("totalClasses", totalClasses);
            
            // 各年级班级数
            QueryWrapper<TcClass> gradeQuery = new QueryWrapper<>();
            gradeQuery.select("grade, count(*) as count");
            gradeQuery.groupBy("grade");
            // 这里可以添加更复杂的统计逻辑
            
            // 班主任班级数
            QueryWrapper<TcClass> headteacherQuery = new QueryWrapper<>();
            headteacherQuery.eq("is_headteacher", 1);
            long headteacherClasses = classService.count(headteacherQuery);
            statistics.put("headteacherClasses", headteacherClasses);
            
            return Result.success("获取班级统计信息成功", statistics);
        } catch (Exception e) {
            return Result.error("获取班级统计信息失败：" + e.getMessage());
        }
    }

    // ==================== 根据WxUser的classId查找TcClass ====================
    
    /**
     * 根据WxUser的classId查找TcClass班级数据
     * @param classId 班级ID
     * @return 班级信息
     */
    @GetMapping("getByClassId/{classId}")
    public Result<TcClass> getClassByClassId(@PathVariable Integer classId) {
        try {
            TcClass result = classService.getClassByClassId(classId);
            if (result == null) {
                return Result.error("班级不存在");
            }
            return Result.success("根据classId获取班级信息成功", result);
        } catch (Exception e) {
            return Result.error("根据classId获取班级信息失败：" + e.getMessage());
        }
    }

    /**
     * 根据WxUser的classId列表批量查找TcClass班级数据（POST方式）
     * @param request 班级ID列表请求对象
     * @return 班级信息列表
     */
    @PostMapping("getByClassIds")
    public Result<List<TcClass>> getClassesByClassIds(@RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Integer> classIds = (List<Integer>) request.get("classIds");
            
            if (classIds == null || classIds.isEmpty()) {
                return Result.error("班级ID列表不能为空");
            }
            
            List<TcClass> result = classService.getClassesByClassIds(classIds);
            return Result.success("根据classId列表获取班级信息成功", result);
        } catch (Exception e) {
            return Result.error("根据classId列表获取班级信息失败：" + e.getMessage());
        }
    }

    /**
     * 根据WxUser的classId列表批量查找TcClass班级数据（GET方式）
     * @param classIds 班级ID列表，用逗号分隔
     * @return 班级信息列表
     */
    @GetMapping("getByClassIds")
    public Result<List<TcClass>> getClassesByClassIdsGet(@RequestParam String classIds) {
        try {
            if (classIds == null || classIds.trim().isEmpty()) {
                return Result.error("班级ID列表不能为空");
            }
            
            List<Integer> classIdList = new ArrayList<>();
            String[] ids = classIds.split(",");
            for (String id : ids) {
                try {
                    classIdList.add(Integer.parseInt(id.trim()));
                } catch (NumberFormatException e) {
                    return Result.error("班级ID格式错误：" + id);
                }
            }
            
            List<TcClass> result = classService.getClassesByClassIds(classIdList);
            return Result.success("根据classId列表获取班级信息成功", result);
        } catch (Exception e) {
            return Result.error("根据classId列表获取班级信息失败：" + e.getMessage());
        }
    }

    // ==================== 三表联查：学生-班级-教师 ====================
    
    /**
     * 三表联查：根据学生ID获取学生-班级-教师信息
     * @param studentId 学生ID
     * @return 学生班级教师关联信息
     */
    @GetMapping("studentClassTeacher/student/{studentId}")
    public Result<StudentClassTeacherDTO> getStudentClassTeacherByStudentId(@PathVariable Long studentId) {
        try {
            StudentClassTeacherDTO result = classService.getStudentClassTeacherByStudentId(studentId);
            if (result == null) {
                return Result.error("学生信息不存在");
            }
            return Result.success("获取学生班级教师信息成功", result);
        } catch (Exception e) {
            return Result.error("获取学生班级教师信息失败：" + e.getMessage());
        }
    }

    /**
     * 三表联查：根据班级ID获取该班级所有学生及其教师信息
     * @param classId 班级ID
     * @return 班级学生教师关联信息列表
     */
    @GetMapping("studentClassTeacher/class/{classId}")
    public Result<List<StudentClassTeacherDTO>> getStudentClassTeacherByClassId(@PathVariable Integer classId) {
        try {
            List<StudentClassTeacherDTO> result = classService.getStudentClassTeacherByClassId(classId);
            return Result.success("获取班级学生教师信息成功", result);
        } catch (Exception e) {
            return Result.error("获取班级学生教师信息失败：" + e.getMessage());
        }
    }

    /**
     * 三表联查：根据教师ID获取该教师所教班级的所有学生信息
     * @param teacherId 教师ID
     * @return 教师班级学生关联信息列表
     */
    @GetMapping("studentClassTeacher/teacher/{teacherId}")
    public Result<List<StudentClassTeacherDTO>> getStudentClassTeacherByTeacherId(@PathVariable Integer teacherId) {
        try {
            List<StudentClassTeacherDTO> result = classService.getStudentClassTeacherByTeacherId(teacherId);
            return Result.success("获取教师班级学生信息成功", result);
        } catch (Exception e) {
            return Result.error("获取教师班级学生信息失败：" + e.getMessage());
        }
    }

    /**
     * 三表联查：获取所有学生-班级-教师关联信息
     * @return 所有学生班级教师关联信息列表
     */
    @GetMapping("studentClassTeacher/all")
    public Result<List<StudentClassTeacherDTO>> getAllStudentClassTeacher() {
        try {
            List<StudentClassTeacherDTO> result = classService.getAllStudentClassTeacher();
            return Result.success("获取所有学生班级教师信息成功", result);
        } catch (Exception e) {
            return Result.error("获取所有学生班级教师信息失败：" + e.getMessage());
        }
    }

    /**
     * 三表联查：根据条件搜索学生-班级-教师信息
     * @param keyword 搜索关键词
     * @param grade 年级
     * @param subject 科目
     * @return 搜索结果列表
     */
    @GetMapping("studentClassTeacher/search")
    public Result<List<StudentClassTeacherDTO>> searchStudentClassTeacher(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String grade,
            @RequestParam(required = false) String subject) {
        try {
            List<StudentClassTeacherDTO> result = classService.searchStudentClassTeacher(keyword, grade, subject);
            return Result.success("搜索学生班级教师信息成功", result);
        } catch (Exception e) {
            return Result.error("搜索学生班级教师信息失败：" + e.getMessage());
        }
    }

    // ==================== 双表联查：用户-班级 ====================
    
    /**
     * 双表联查：查询所有用户及其班级信息
     * @return 所有用户及其班级信息列表
     */
    @GetMapping("allUserWithClass")
    public Result<List<Map<String, Object>>> getAllUserWithClass() {
        try {
            System.out.println("=== 开始执行 getAllUserWithClass 方法 ===");
            List<Map<String, Object>> result = classService.getAllUserWithClass();
            System.out.println("=== 查询结果数量: " + (result != null ? result.size() : "null") + " ===");
            if (result != null && !result.isEmpty()) {
                System.out.println("=== 第一条数据: " + result.get(0) + " ===");
            }
            return Result.success("查询所有用户及其班级信息成功", result);
        } catch (Exception e) {
            System.out.println("=== 查询异常: " + e.getMessage() + " ===");
            e.printStackTrace();
            return Result.error("查询所有用户及其班级信息失败：" + e.getMessage());
        }
    }

    /**
     * 测试数据库连接和表数据
     * @return 测试结果
     */
    @GetMapping("testDatabase")
    public Result<Map<String, Object>> testDatabase() {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 测试wx_user表
            System.out.println("=== 测试wx_user表 ===");
            List<Map<String, Object>> wxUsers = classService.testWxUserTable();
            result.put("wx_user_count", wxUsers != null ? wxUsers.size() : 0);
            result.put("wx_user_sample", wxUsers != null && !wxUsers.isEmpty() ? wxUsers.get(0) : null);
            
            // 测试tc_class表
            System.out.println("=== 测试tc_class表 ===");
            List<TcClass> tcClasses = classService.list();
            result.put("tc_class_count", tcClasses != null ? tcClasses.size() : 0);
            result.put("tc_class_sample", tcClasses != null && !tcClasses.isEmpty() ? tcClasses.get(0) : null);
            
            // 测试LEFT JOIN
            System.out.println("=== 测试LEFT JOIN ===");
            List<Map<String, Object>> leftJoinResult = classService.testLeftJoin();
            result.put("left_join_count", leftJoinResult != null ? leftJoinResult.size() : 0);
            result.put("left_join_sample", leftJoinResult != null && !leftJoinResult.isEmpty() ? leftJoinResult.get(0) : null);
            
            return Result.success("数据库测试完成", result);
        } catch (Exception e) {
            System.out.println("=== 数据库测试异常: " + e.getMessage() + " ===");
            e.printStackTrace();
            return Result.error("数据库测试失败：" + e.getMessage());
        }
    }

    /**
     * 双表联查：查询所有学生及其班级信息
     * @return 所有学生及其班级信息列表
     */
    @GetMapping("allStudentWithClass")
    public Result<List<Map<String, Object>>> getAllStudentWithClass() {
        try {
            List<Map<String, Object>> result = classService.getAllStudentWithClass();
            return Result.success("查询所有学生及其班级信息成功", result);
        } catch (Exception e) {
            return Result.error("查询所有学生及其班级信息失败：" + e.getMessage());
        }
    }

    /**
     * 双表联查：根据班级ID查询该班级所有用户及其班级信息
     * @param classId 班级ID
     * @return 该班级所有用户及其班级信息列表
     */
    @GetMapping("classUsersWithClass/{classId}")
    public Result<List<Map<String, Object>>> getClassUsersWithClass(@PathVariable Integer classId) {
        try {
            List<Map<String, Object>> result = classService.getClassUsersWithClass(classId);
            return Result.success("查询班级用户及其班级信息成功", result);
        } catch (Exception e) {
            return Result.error("查询班级用户及其班级信息失败：" + e.getMessage());
        }
    }

    /**
     * 双表联查：根据班级ID查询该班级所有学生及其班级信息
     * @param classId 班级ID
     * @return 该班级所有学生及其班级信息列表
     */
    @GetMapping("classStudentsWithClass/{classId}")
    public Result<List<Map<String, Object>>> getClassStudentsWithClass(@PathVariable Integer classId) {
        try {
            List<Map<String, Object>> result = classService.getClassStudentsWithClass(classId);
            return Result.success("查询班级学生及其班级信息成功", result);
        } catch (Exception e) {
            return Result.error("查询班级学生及其班级信息失败：" + e.getMessage());
        }
    }

    
}
